package com.example.demo.juc.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Description: 实现让一组线程等待至某个状态之后再全部同时执行。叫做回环
 * 是因为当所有等待线程都被释放以后，CyclicBarrier 可以被重用。
 * @Author: xiatian
 * @CreateTime: 2021/9/7
 * @Company: kangxu
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        int n = 4;
        CyclicBarrier barrier = new CyclicBarrier(n);
        for (int i = 0; i < n; i++) {
            new Writer(barrier).start();
        }
    }

    static class Writer extends Thread {
        private CyclicBarrier cyclicBarrier;

        public Writer(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                //以睡眠来模拟线程需要预定写入数据操作
                Thread.sleep(5000);
                System.out.println(" 线程 " + Thread.currentThread().getName() + "写入数据完毕，等待其他线程先入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入完毕，继续处理其他任务，比如数据操作");

        }
    }
}
